package com.bungarus.group.controller;

import com.bungarus.group.model.BungarusError;
import com.bungarus.ratelimit.RateLimitExceedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * Created by tang on 2018/12/14.
 */
public abstract class BungarusController {
    @ExceptionHandler({IllegalArgumentException.class, Exception.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BungarusError dealException(Exception thrownException) {
        Exception e;
        if(thrownException instanceof UndeclaredThrowableException) {
            e = (Exception) thrownException.getCause();
        }
        else {
            e = thrownException;
        }
        BungarusError.Builder errorBuilder = BungarusError.newBuilder()
                .message(e.getMessage());
        if(e instanceof RateLimitExceedException) {
            RateLimitExceedException ree = (RateLimitExceedException)e;
            errorBuilder.code(HttpStatus.TOO_MANY_REQUESTS.value());
            errorBuilder.user_msg("Request frequency less than " + ree.getLimit() + " per " + ree.getUnit() + " is permitted.");
        }
        return errorBuilder.build();
    }
}
